#!/bin/bash
#---------------设置ssh免密登入---------------#
HOST_IP_NODE=192.168.56.22
HOST_PASS_NODE=123456


# 定义公钥和私钥文件的路径  
public_key_path="/root/.ssh/id_rsa.pub"
private_key_path="/root/.ssh/id_rsa"

# 检查公钥文件是否存在  
if [  -f "$public_key_path && $private_key_path "  ];
then
echo "秘钥文件不存在，开始创建..."  
#安装expect软件包
apt install expect -y
expect << EOF
set timeout 5
spawn ssh-keygen -t rsa
expect "id_rsa):" 
send "\r" 
expect "passphrase):" 
send "\r"
expect "again:"
send "\r" 
expect eof
EOF
echo "秘钥文件创建成功！"  

else
   echo "秘钥文件已存在"
fi

echo "正在分发公钥到远程主机"

expect << EOF
set timeout 5
spawn ssh-copy-id root@$HOST_IP_NODE
#expect "(yes/no)?" 
#send "yes\r"
expect "password:" 
send "$HOST_PASS_NODE\r" 
expect eof
EOF

echo "秘钥分发成功"
